package com.tourism.tourismGYM.commom;

import java.math.BigInteger;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.util.Assert;
/**
 * 分页简化类
 * @author gym<br>
 */
@SuppressWarnings("all")
public class BasePage {
	public Integer page;
	public Integer pageSize;
	public Map<String, Object> map;
	public BasePage(Map<String, Object> map){
		this.map = map;
		this.page = Integer.valueOf(map.get("page").toString());
		this.pageSize = Integer.valueOf(map.get("pageSize").toString());
	}
	public Integer getPage() {
		return page;
	}

	public Integer getPageSize() {
		return pageSize;
	}

	public  Pageable getPageable(String sort) {
		Assert.notEmpty(map,map.get("page").toString());
		Pageable pageable = null;
		if(sort.equals("")) {
			pageable = new PageRequest(page.intValue(),pageSize.intValue());
		}else{
			pageable = new PageRequest(page.intValue(),pageSize.intValue(), Sort.Direction.DESC, sort);
		}
		return pageable;
	}
	public static Page<HashMap> getPageResult(EntityManager entityManager, Pageable pageable, String sql){
		//创建本地sql查询实例
		Query dataQuery = entityManager.createNativeQuery(sql);
		dataQuery.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
		String countSql = sql.substring(sql.indexOf("from"), sql.indexOf("group by")==-1?sql.length():sql.indexOf("group by"));
		Query countQuery = entityManager.createNativeQuery("select count(1) " + countSql);
		
		//设置分页
		dataQuery.setFirstResult(pageable.getOffset());
		dataQuery.setMaxResults(pageable.getPageSize());
		BigInteger count = (BigInteger) countQuery.getSingleResult();
		Long total = count.longValue();
//				List<Map> rows = dataQuery.getResultList();
		List<HashMap> content2 = total > pageable.getOffset() ? dataQuery.getResultList() : Collections.<HashMap> emptyList();
		return new PageImpl<>(content2, pageable, total);
	}
	
}
